package com.example.orderservice.service;

import com.example.orderservice.client.ProductClient;
import com.example.orderservice.dto.OrderItemRequest;
import com.example.orderservice.dto.OrderRequest;
import com.example.orderservice.exception.InsufficientStockException;
import com.example.orderservice.model.Order;
import com.example.orderservice.model.OrderItem;
import com.example.orderservice.model.OrderStatus;
import com.example.orderservice.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单服务实现类
 * 提供订单相关的业务逻辑处理，包括订单创建、查询、状态管理等
 * 
 * @author SimpleShop
 * @version 1.0
 */
@Service
public class OrderService {

    /**
     * 订单数据访问对象
     */
    private final OrderRepository orderRepository;
    
    /**
     * 商品服务客户端
     */
    private final ProductClient productClient;

    /**
     * 构造函数，注入依赖
     * 
     * @param orderRepository 订单数据访问对象
     * @param productClient 商品服务客户端
     */
    @Autowired
    public OrderService(OrderRepository orderRepository, ProductClient productClient) {
        this.orderRepository = orderRepository;
        this.productClient = productClient;
    }

    /**
     * 创建订单
     */
    @Transactional
    public Order createOrder(OrderRequest orderRequest) {
        Order order = new Order();
        order.setUserId(orderRequest.getUserId());
        order.setStatus(OrderStatus.CREATED);

        BigDecimal totalAmount = BigDecimal.ZERO;

        // 处理每个订单项
        for (OrderItemRequest itemRequest : orderRequest.getItems()) {
            // 调用商品服务获取商品信息
            ProductClient.ProductDTO product = productClient.getProductById(itemRequest.getProductId());

            // 检查库存
            if (product.getStock() < itemRequest.getQuantity()) {
                throw new InsufficientStockException("商品库存不足: " + product.getName());
            }

            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductPrice(product.getPrice());
            orderItem.setQuantity(itemRequest.getQuantity());

            // 添加到订单
            order.addItem(orderItem);

            // 计算小计并累加到总金额
            BigDecimal subtotal = product.getPrice().multiply(BigDecimal.valueOf(itemRequest.getQuantity()));
            totalAmount = totalAmount.add(subtotal);

            // 扣减库存（调用商品服务）
            productClient.reduceStock(product.getId(), itemRequest.getQuantity());
        }

        order.setTotalAmount(totalAmount);

        // 保存订单
        return orderRepository.save(order);
    }

    /**
     * 根据ID获取订单
     */
    public Order getOrderById(Long id) {
        return orderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("订单未找到, ID: " + id));
    }

    /**
     * 根据用户ID获取订单列表
     */
    public List<Order> getOrdersByUserId(Long userId) {
        return orderRepository.findByUserId(userId);
    }

    /**
     * 更新订单状态
     */
    @Transactional
    public Order updateOrderStatus(Long id, OrderStatus status) {
        Order order = getOrderById(id);
        order.setStatus(status);
        return orderRepository.save(order);
    }

    /**
     * 处理伪支付
     * @param orderId 订单ID
     * @return 支付成功后的订单
     */
    @Transactional
    public Order processPayment(Long orderId) {
        Order order = getOrderById(orderId);

        // 检查订单状态是否为待支付
        if (order.getStatus() != OrderStatus.CREATED) {
            throw new RuntimeException("订单状态异常，无法支付");
        }

        // 伪支付处理 - 简单更新状态为已支付
        order.setStatus(OrderStatus.PAID);

        // 可以在此处添加支付日志记录等操作

        return orderRepository.save(order);
    }
}